package com.caiyi.financial.nirvana.sms.task;

import com.alibaba.fastjson.JSON;
import com.caiyi.financial.nirvana.sms.entity.SmsReceiveMessage;
import com.caiyi.financial.nirvana.sms.entity.SmsUser;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.jedis.JedisService;
import com.caiyi.financial.nirvana.sms.util.CommUtil;
import com.caiyi.financial.nirvana.sms.util.HttpClientUtil;
import com.caiyi.financial.nirvana.sms.util.SignUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Mario on 2018/3/12 0012.
 * 推送上行短信Task
 */
public class PushReceiveTask implements Runnable {
    private static final Logger logger = LoggerFactory.getLogger(PushReceiveTask.class);

    private SmsReceiveMessage smsReceiveMessage;

    public PushReceiveTask(SmsReceiveMessage entity) {
        this.smsReceiveMessage = entity;
    }

    /**
     * 推送上行短信到客户
     */
    @Override
    public void run() {
        try {
            //查询Redis获取客户推送地址
            String key = String.format(JedisKey.SMS_USER, smsReceiveMessage.getAccount());
            String jsonUser = JedisService.get(key);
            SmsUser user = JSON.parseObject(jsonUser, SmsUser.class);
            String receiveUrl = user.getReceiveUrl();
            if (StringUtils.isBlank(receiveUrl)) {
                logger.info("账户：{} - 未配置上行短信推送地址。", smsReceiveMessage.getAccount());
                return;
            }
            //推送参数
            Map<String, String> pushMap = new HashMap<>();
            pushMap.put("account", smsReceiveMessage.getAccount());
            pushMap.put("messageId", smsReceiveMessage.getMessageId());
            pushMap.put("phone", smsReceiveMessage.getPhone());
            pushMap.put("content", smsReceiveMessage.getContent());
            pushMap.put("accessNumber", smsReceiveMessage.getAccessNumber());
            pushMap.put("receiveTime", CommUtil.YYYY_MM_DD_HH_MM_SS.get().format(smsReceiveMessage.getCreateTime()));
            String sign = SignUtil.createSign(pushMap, user.getPassword());
            pushMap.put("sign", sign);
            String response = HttpClientUtil.doPost(receiveUrl, JSON.toJSONString(pushMap));
            logger.info("{}上行推送，内容：{}，推送结果：{}", smsReceiveMessage.getAccount(), pushMap, response);
        } catch (Exception e) {
            logger.error("pushReceiveMessage error", e);
        }
    }
}
